import { mapKey } from '@/config'
import myFetch from '@/assets/utils/myFetch'

/**
 * @param callback 回调函数
 *  @description callback(ip:string)=>{console.log(ip)}
 * */
function getUserIP(callback: Function) {
	let ip_dups: { [x: string]: boolean } = {}
	let RTCPeerConnection =
		window.RTCPeerConnection ||
		window.mozRTCPeerConnection ||
		window.webkitRTCPeerConnection
	// var useWebKit = !!window.webkitRTCPeerConnection
	let mediaConstraints = {
		optional: [{ RtpDataChannels: true }],
	}
	// 这里就是需要的ICEServer了
	let servers = {
		iceServers: [
			{ urls: 'stun:stun.services.mozilla.com' },
			{ urls: 'stun:stun.l.google.com:19302' },
		],
	}
	let pc = new RTCPeerConnection(servers, mediaConstraints)

	function handleCandidate(candidate: string) {
		let ip_regex =
			/([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
		let hasIp = ip_regex.exec(candidate)
		if (hasIp) {
			let ip_addr: string = hasIp[1]
			if (ip_dups[ip_addr] === undefined) callback(ip_addr)
			ip_dups[ip_addr] = true
		}
	}

	// 网络协商的过程
	pc.onicecandidate = function (ice) {
		if (ice.candidate) {
			handleCandidate(ice.candidate.candidate)
		}
	}
	pc.createDataChannel('')
	//创建一个SDP(session description protocol)会话描述协议 是一个纯文本信息 包含了媒体和网络协商的信息
	pc.createOffer(
		function (result) {
			pc.setLocalDescription(
				result,
				function () {},
				function () {},
			)
		},
		function () {},
	)
	setTimeout(function () {
		let lines = pc.localDescription?.sdp.split('\n') as Array<any>
		lines.forEach(function (line) {
			if (line.indexOf('a=candidate:') === 0) handleCandidate(line)
		})
	}, 1000)
}

/**
 * @param ip:string
 * @return Promise<string>
 * */
function getCityCode(ip: string) {
	return new Promise<string>(resolve => {
		myFetch(`https://restapi.amap.com/v3/ip?key=${mapKey}&ip=${ip}`).then(
			(value: any) => {
				resolve(value.adcode)
			},
		)
	})
}

/**
 * @param cityCode:string
 * @return Promise<string>
 * */
function getWeather(cityCode: string) {
	return new Promise<string>(resolve => {
		myFetch(
			`https://restapi.amap.com/v3/weather/weatherInfo?key=${mapKey}&city=${cityCode}&extensions=base`,
		).then((value: any) => {
			resolve(value.lives[0].weather)
		})
	})
}

export { getUserIP, getCityCode, getWeather }
